import { routerRedux } from 'dva/router';
import { login, logout, getCurrentUser } from '@/services/user';
import { setToken, getToken } from '@/utils/authority2';

export default {
  namespace: 'user',

  state: {
    list: [],
    currentUser: {},
  },

  effects: {
    *login({payload}, { call, put }) {
      const response = yield call(login, payload);
      console.log("============>>>>>从后台获得的token", response.data)
      if(response.status === 0 ) {
        yield setToken(response.data);
        console.log("============>>>>>登录后设置的token", getToken())
        debugger
        yield put(routerRedux.push('/'));
      }
    },
    *logout(_, { call, put }) {
      const response = yield call(logout);
      if(response.status === 0 ) {
        // setToken(response.data);
        // 跳转到登录页面
        yield put(routerRedux.push('/user/login'));
        // 清理用户数据
        yield put({
          type: 'save',
          payload: { currentUser: {}},
        });
        // 清理缓存
        setToken(null)
      }
    },
    *getCurrentUser({payload}, { call, put }) {
      console.log("============>>>>>登录后设置的token", getToken())
      const response = yield call(getCurrentUser, payload);
      if(response.status === 0 ) {
        yield put({
          type: 'save',
          payload: { currentUser: response.data},
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
